package im430.santashelper.springmvc;

import im430.santashelper.business.Child;
import im430.santashelper.dao.ChildDAO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/children")
public class ChildrenController {

	private ChildDAO childDAO;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public void listChildren(Model model) {
		model.addAttribute("children", getChildDAO().getAllChildren());
	}

	@RequestMapping(value = "/read/{id}", method = RequestMethod.GET)
	public String viewChild(@PathVariable int id, Model model) {	
		model.addAttribute("child", getChildDAO().getChildById(id));
		return "children/read";
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public void formCreateChild(@ModelAttribute Child child) {	
		child = new Child();
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String createChild(Child child) {
		getChildDAO().addChild(child);
		return "redirect:../children/list";
	}

	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String formUpdateChild(@PathVariable int id, @ModelAttribute Child child, Model model) {
		child = getChildDAO().getChildById(id);
		model.addAttribute("childData", child);
		return "children/update";
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String updateChild(Child child) {
		getChildDAO().updateChild(child);
		return "redirect:../list";
	}
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String confirmDeleteChild(@PathVariable int id, Model model) {	
		model.addAttribute("child", getChildDAO().getChildById(id));
		return "children/delete";
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	public String deleteChild(@PathVariable int id) {
		getChildDAO().removeChild(getChildDAO().getChildById(id));
		return "redirect:../list";
	}

	public ChildDAO getChildDAO() {
		return childDAO;
	}

	@Autowired
	public void setChildDAO(ChildDAO childDAO) {
		this.childDAO = childDAO;
	}

}